<template>
  <div class="state-management-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="header-left">
          <h1>状态管理</h1>
          <p class="header-description">管理系统中各模块的状态配置</p>
        </div>
        <div class="header-right">
          <a-button @click="handleRefresh" :loading="refreshing">
            <template #icon>
              <ReloadOutlined />
            </template>
            刷新
          </a-button>
        </div>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="page-content">
      <a-row :gutter="24">
        <!-- 状态列表区域 -->
        <a-col :xs="24" :lg="18">
          <a-card class="state-config-card" :bordered="false">
            <template #title>
              <span class="card-title">状态配置</span>
            </template>
            <StateList ref="stateListRef" />
          </a-card>
        </a-col>
        
        <!-- 模块筛选侧边栏 -->
        <a-col :xs="24" :lg="6">
          <a-card class="module-filter-card" :bordered="false">
            <template #title>
              <span class="card-title">模块筛选</span>
            </template>
            <div class="module-filter">
              <a-spin :spinning="loadingModules">
                <div v-if="moduleTypes.length > 0" class="module-list">
                  <div
                    v-for="moduleType in moduleTypes"
                    :key="moduleType.value"
                    class="module-item"
                    :class="{ 'module-item-active': selectedModule === moduleType.value }"
                    @click="handleSelectModule(moduleType.value)"
                  >
                    <div class="module-info">
                      <div class="module-name-wrapper">
                        <a-tag :color="moduleType.color" class="module-tag">
                          {{ moduleType.label }}
                        </a-tag>
                      </div>
                      <div class="module-stats" v-if="getModuleStats(moduleType.value)">
                        <span class="stats-text">{{ getModuleStats(moduleType.value) }} 个状态</span>
                      </div>
                    </div>
                    <div class="module-actions" @click.stop>
                      <a-tooltip title="同步默认状态">
                        <a-button
                          type="text"
                          size="small"
                          class="init-btn"
                          :loading="initializingModule === moduleType.value"
                          @click="handleInitModule(moduleType.value)"
                        >
                          <template #icon>
                            <SyncOutlined />
                          </template>
                        </a-button>
                      </a-tooltip>
                    </div>
                  </div>
                </div>
                <a-empty v-else description="暂无模块信息" :image="false" />
              </a-spin>
            </div>
          </a-card>
        </a-col>
      </a-row>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { ReloadOutlined, SyncOutlined } from '@ant-design/icons-vue'
import { ModuleType } from '@/types/state'
import { useStateStore } from '@/stores/state'
import StateList from '@/components/state/StateList.vue'
import { MODULE_TYPES, getModuleLabel } from '@/utils/moduleTypes'

const stateStore = useStateStore()
const stateListRef = ref()
const refreshing = ref(false)
const loadingModules = ref(false)
const initializingModule = ref<ModuleType | null>(null)
const selectedModule = ref<ModuleType | null>(null)

// 使用统一的模块类型配置
const moduleTypes = MODULE_TYPES

// 从store获取状态数据
const states = computed(() => stateStore.states)

// 获取模块统计信息
const getModuleStats = (moduleType: ModuleType): number => {
  return states.value.filter(state => state.module_type === moduleType).length
}

// 处理初始化模块
const handleInitModule = async (moduleType: ModuleType) => {
  initializingModule.value = moduleType
  
  try {
    const result = await stateStore.initModuleStates(moduleType)
    // 显示详细的初始化结果
    const parts = []
    if (result.created_count > 0) {
      parts.push(`创建${result.created_count}个状态`)
    }
    if (result.updated_count > 0) {
      parts.push(`更新${result.updated_count}个状态`)
    }
    if (result.disabled_count > 0) {
      parts.push(`禁用${result.disabled_count}个不在默认列表中的状态`)
    }
    if (parts.length > 0) {
      message.success(`${getModuleLabel(moduleType)}模块状态同步成功，${parts.join('，')}`)
    } else {
      message.info(`${getModuleLabel(moduleType)}模块状态已是最新，无需更新`)
    }
    await handleRefresh()
  } catch (error) {
    console.error('初始化模块状态失败:', error)
    message.error(`${getModuleLabel(moduleType)}模块状态初始化失败`)
  } finally {
    initializingModule.value = null
  }
}

// 处理刷新
const handleRefresh = async () => {
  refreshing.value = true
  try {
    // 只调用StateList组件的loadStates方法，避免重复调用
    await stateListRef.value?.loadStates?.()
    message.success('刷新成功')
  } catch (error) {
    console.error('刷新失败:', error)
    message.error('刷新失败')
  } finally {
    refreshing.value = false
  }
}

// 处理选择模块
const handleSelectModule = (moduleType: ModuleType) => {
  selectedModule.value = moduleType
  // 通知状态列表组件切换模块
  stateListRef.value?.setModuleFilter?.(moduleType)
}

onMounted(() => {
  // StateList组件会在自己的onMounted中加载数据，这里不需要重复调用
})
</script>

<style scoped>
.state-management-page {
  padding: 24px;
  background: #f5f5f5;
  min-height: calc(100vh - 64px);
}

/* 页面头部 */
.page-header {
  margin-bottom: 24px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #fff;
  padding: 20px 24px;
  border-radius: 8px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.03);
}

.header-left h1 {
  margin: 0 0 4px 0;
  font-size: 20px;
  font-weight: 600;
  color: #262626;
}

.header-description {
  margin: 0;
  color: #8c8c8c;
  font-size: 14px;
}

/* 主要内容区域 */
.page-content {
  width: 100%;
}

.state-config-card,
.module-filter-card {
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.03);
}

.card-title {
  font-size: 16px;
  font-weight: 500;
  color: #262626;
}

/* 模块筛选卡片 */
.module-filter {
  padding: 0;
}

.module-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.module-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 14px 16px;
  border: 1px solid #f0f0f0;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
  background: #fff;
  position: relative;
}

.module-item::before {
  content: '';
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  width: 3px;
  background: transparent;
  transition: background 0.2s;
}

.module-item:hover {
  border-color: #d9d9d9;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.06);
  transform: translateY(-1px);
}

.module-item:hover::before {
  background: #1890ff;
}

.module-item-active {
  border-color: #1890ff;
  background: #f0f8ff;
}

.module-item-active::before {
  background: #1890ff;
}

.module-info {
  flex: 1;
  min-width: 0;
}

.module-name-wrapper {
  margin-bottom: 6px;
}

.module-tag {
  margin: 0;
  font-size: 13px;
  border: none;
}

.module-stats {
  font-size: 12px;
  color: #8c8c8c;
}

.stats-text {
  display: inline-flex;
  align-items: center;
}

.module-actions {
  display: flex;
  align-items: center;
  margin-left: 8px;
}

.init-btn {
  color: #8c8c8c;
}

.init-btn:hover {
  color: #1890ff;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .page-content :deep(.ant-row) {
    flex-direction: column;
  }
  
  .page-content :deep(.ant-col) {
    width: 100% !important;
    max-width: 100% !important;
    flex: none !important;
  }
}

@media (max-width: 768px) {
  .state-management-page {
    padding: 16px;
  }
  
  .header-content {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
    padding: 16px;
  }
  
  .header-left h1 {
    font-size: 18px;
  }
  
  .module-item {
    padding: 12px;
  }
  
  .module-tag {
    font-size: 12px;
  }
}
</style>